﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using WebAppIdentity.DbContext;
namespace WebAppIdentity.Services
{
	public class ThirdClientService : IThirdClientService
	{
		private readonly UserDbContext _appDbContext;
		private readonly IMemoryCache _memoryCache;

		public ThirdClientService(UserDbContext appDbContext, IMemoryCache memoryCache)
		{
			_appDbContext = appDbContext;
			_memoryCache = memoryCache;
		}

		public async Task<ThirdClient?> CreateThirdClient(string AppKey)
		{
			if (string.IsNullOrEmpty(AppKey))
			{
				await Task.CompletedTask;
				return null;
			}
			var appSecret = Guid.NewGuid().ToString().Replace("-", "");
			ThirdClient thirdClient = new() { AppKey = AppKey, AppSecret = appSecret };
			_appDbContext.ThirdClients.Add(thirdClient);
			await _appDbContext.SaveChangesAsync();
			return thirdClient;
		}

		public async Task<string> GetToken(ThirdClient thirdClient)
		{
			var cacheKey = "thirdClient_" + thirdClient.AppKey;
			if (_memoryCache.TryGetValue(cacheKey, out var cacheToken))
			{
				return cacheToken?.ToString() ?? "";
			}
			var exist = await _appDbContext.ThirdClients.AnyAsync(p => p.AppKey == thirdClient.AppKey && p.AppSecret == thirdClient.AppSecret);
			if (!exist)
			{
				return string.Empty;
			}
			var token = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
			_memoryCache.Set(cacheKey, token, TimeSpan.FromMinutes(10));
			return token;
		}

		public async Task<IList<ThirdClient>> QueryList()
		{
			return await _appDbContext.ThirdClients.ToListAsync();
		}
	}
}
